<?php

namespace app\company\controller;

use app\company\service\CustomerService;
use app\exception\MsgException;
use support\Request;
use support\Response;
use Throwable;

/**
 * 客户管理
 * @api
 */
class Customer extends Base
{

    /**
     * 获取表格数据
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function lists(Request $request): Response
    {
        $params = $request->all();
        $service = new CustomerService();

        $params['cid'] = $this->getPayload('cid');

        //导出表格
        if(!empty($params['is_export'])){
            $res = $service->exportExcel($params);
            return $this->withData(0, '导出成功', $res);
        }

        $list = $service->getList($params);
        return $this->withData(0, 'success', $list);
    }

    /**
     * 新增
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function add(Request $request): Response
    {
        $data = $request->all();
        $service = new CustomerService();
        if(!empty($data['id'])){
            throw new MsgException("新增数据不可传入ID");
        }

        $data['cid'] = $this->getPayload('cid');

        $res = $service->add($data);
        return $this->withData(0, '新增成功', $res);
    }

    /**
     * 编辑
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function edit(Request $request): Response
    {
        $data = $request->all();
        $service = new CustomerService();
        $data['cid'] = $this->getPayload('cid');

        if(empty($data['id'])){
            throw new MsgException("编辑数据需传入ID");
        }

        //还原回收站
        if(!empty($data['is_reduction'])){
            $service->reduction($data['id']);
            return $this->withData(0, '还原成功');
        }

        $res = $service->edit($data);
        return $this->withData(0, '编辑成功', $res);
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function delete(Request $request): Response
    {
        $ids = $request->post('ids');
        $isRecycle = $request->post('is_recycle', 0);

        $service = new CustomerService();
        $res = $service->delete($ids, (bool)$isRecycle);
        return $this->withData(0, '删除成功', $res);
    }

}